package cn.sinothk.view.treeView.demo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import cn.sinothk.view.treeView.bean.Node
import cn.sinothk.view.treeView.bean.TreeItemBean
import com.alibaba.fastjson.JSON
import kotlinx.android.synthetic.main.activity_main.*
import java.util.ArrayList

class MainActivity : AppCompatActivity() {

    private var mCommonTreeAdapter: CommonTreeAdapter? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        initAdapter()
    }

    private fun initAdapter() {

        initData()

        mCommonTreeAdapter = CommonTreeAdapter(
            treeListView, this, mTreeData,
            1, R.drawable.ic_checkbox_checked, R.drawable.ic_checkbox_uncheck
        )

        mCommonTreeAdapter!!.setOnItemCheckedListener { seletcedNodes, position, node, isCheck ->
            Toast.makeText(this@MainActivity, node.name, Toast.LENGTH_LONG).show()
        }
        treeListView!!.adapter = mCommonTreeAdapter
    }

    private fun initData() {
        val treeData: String =
            "[{\"id\":\"4\",\"pid\":\"1\",\"name\":\"第一党小组\"},{\"id\":\"5\",\"pid\":\"1\",\"name\":\"第二党小组\"},{\"id\":\"1\",\"pid\":\"0\",\"name\":\"总公办\"},{\"id\":\"2\",\"pid\":\"0\",\"name\":\"党总支\"},{\"id\":\"13\",\"pid\":\"2\",\"name\":\"第一党支部\"}]"

        val treeItemBeanList = JSON.parseArray(treeData, TreeItemBean::class.java)
        mTreeData = getNodelis(treeItemBeanList)
    }

    open fun getNodelis(treeItemBeanList: List<TreeItemBean>): ArrayList<Node<*, *>> {
        val nodeList: ArrayList<Node<*, *>> = ArrayList()
        if (treeItemBeanList.isNotEmpty()) {
            for (treeItemBean in treeItemBeanList) {
                val node: Node<String, TreeItemBean> =
                    Node(
                        treeItemBean.id,
                        treeItemBean.pid,
                        treeItemBean.name
                    )
                node.setBean(treeItemBean)
                nodeList.add(node)
            }
        }
        return nodeList
    }

    private var mTreeData: ArrayList<Node<*, *>>? = null
}